<?php

/**
 * This is the model class for table "{{user}}".
 *
 * The followings are the available columns in table '{{user}}':
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $title
 * @property string $firstName
 * @property string $lastName
 * @property string $contactPhone
 * @property string $email
 * @property integer $teamId
 * @property integer $globalView
 * @property integer $active
 *
 * The followings are the available model relations:
 * @property Communication[] $communications
 * @property Team $team
 */
class User extends CActiveRecord
{
	private static $_currentUser;
	/**
	 * Returns the static model of the specified AR class.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * Get the active record object for current login user
	 * @return User the active record object for current login user.
	 */
	public static function getCurrentUser(){
		if(self::$_currentUser==null){
			self::$_currentUser=self::model()->findByPk(Yii::app()->user->id);
		}
		return self::$_currentUser;
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{user}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('username, password, title, firstName, lastName, contactPhone, email, globalView, active', 'required'),
			array('teamId','required','on'=>'insert'),
			array('username','unique','on'=>'insert'),
			array('teamId, active, globalView, teamLeader', 'numerical', 'integerOnly'=>true),
			array('username, password, title, firstName, lastName, contactPhone, email', 'length', 'max'=>255),
			array('username', 'match', 'not'=>true, 'pattern'=>"/[^0-9A-Za-z_\.\-]+/i", 'message'=>'Username only allows letters, numbers, dot, dash and underscore'),
			array('password', 'match', 'not'=>true, 'pattern'=>"/[^0-9A-Za-z_\.\-]+/i", 'message'=>'Password only allows letters, numbers, dot, dash and underscore'),
			array('email','email'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, username, password, title, firstName, lastName, contactPhone, email, teamId, active', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'communications' => array(self::HAS_MANY, 'Communication', 'createUser'),
			'team' => array(self::BELONGS_TO, 'Team', 'teamId'),
			//'customers'=>array(self::HAS_MANY,'Customer','teamId','through'=>'team'),
		);
	}

	public function scopes(){
		return array(
			'active'=>array(
		            'condition'=>'active=1',
			),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'username' => 'Username',
			'password' => 'Password',
			'title' => 'Title',
			'firstName' => 'First Name',
			'lastName' => 'Last Name',
			'contactPhone' => 'Contact Phone',
			'email' => 'Email',
			'teamId' => 'Team',
			'active' => 'Active',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		//$criteria->compare('id',$this->id);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('password',$this->password,true);
		//$criteria->compare('title',$this->title,true);
		$criteria->compare('firstName',$this->firstName,true);
		$criteria->compare('lastName',$this->lastName,true);
		//$criteria->compare('contactPhone',$this->contactPhone,true);
		//$criteria->compare('email',$this->email,true);
		$criteria->compare('teamId',$this->teamId);
		$criteria->compare('active',$this->active);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
	
	public static function checkCustomerInfoAccess($customerId) {
		// manager has global access to customer.
		if(Yii::app()->user->checkAccess('manager')){
			return true;
		}
		
		if($customerId){
			$customer=Customer::model()->findByPk($customerId);
			$user=self::getCurrentUser();
			
			// Block Reception.
			if($user->isReception())
				return false;
			
			// If user is a team leader, check if the customer is in his team.
			if($user->teamLeader==DataUtil::VALUE_YES){
				if($customer->teamId && $customer->teamId==$user->teamId){
					return true;
				}
			}
			
			// Check if the user is the create user.
			if($customer->createUserId && $customer->createUserId==$user->id){
				return true;
			}
		}
		return false;
	}

	public static function checkCustomerInfoView($customerId) {
		if(Yii::app()->user->checkAccess('manager')){
			return true;
		}
		$user=self::getCurrentUser();
		if($user->globalView){
			return true;
		}
		if($customerId){
			$customer=Customer::model()->findByPk($customerId);
			$user=self::getCurrentUser();
			
			// Block Reception.
			if($user->isReception())
				return false;
			
			if($user->teamLeader==DataUtil::VALUE_YES){
				if($customer->teamId && $customer->teamId==$user->teamId){
					return true;
				}
			}
			if($customer->createUserId && $customer->createUserId==$user->id){
				return true;
			}
		}
		return false;
	}
	
	public static function checkDealInfoAccess($dealId) {
		// manager has global access to deal.
		if(Yii::app()->user->checkAccess('manager')){
			return true;
		}
		
		if($dealId){
			$deal=Deal::model()->findByPk($dealId);
			$user=self::getCurrentUser();
			
			// Block Reception.
			if($user->isReception())
				return false;
			
			// If user is a team leader, check if the deal is in his team.
			if($user->teamLeader==DataUtil::VALUE_YES){
				if($deal->teamId && $deal->teamId==$user->teamId){
					return true;
				}
			}
			
			// Check if the user is the create user.
			if($deal->createUserId && $deal->createUserId==$user->id){
				return true;
			}
		}
		return false;
	}
	
	public static function getAllByTeam($teamId) {
		return self::model()->findAll(array(
			'condition'=>'teamId=:teamId',
			'params'=>array(':teamId'=>$teamId),
		));
	}
	
	public function getFullName() {
		return $this->firstName.' '.$this->lastName;
	}
	
	public function isReception(){
		return $this->teamId == 100 && $this->active;
	}
}